<?php

/**
 * 分页导航显示类
 * 
 * @author keluo<pycorvn@yeah.net>
 * @since 2015-02-06
 */
class SCPage {
    
    public $current; // 当前页码
    public $total = 0; // 记录总数
    public $size = 10; // 每页显示记录数
    public $column = 5; // 导航显示最大分页栏数
    
    private static $_instance;
    
    private function __construct() {
        $this->current = (SCS::request()->param('page') >= 1) ? intval(SCS::request()->param('page')) : 1;
    }
    
    public function __clone() {}
    
    public static function instance() {
        if(!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    
    /**
     * 获取分页导航串形如：<< 2 3 4 5 ６ 7 8 9 10 11 >>
     * 可自定义每一项页码html格式，每一项必须包含{url}、{page}、{active}占位符，
     * {url}表示当前项url，{page}表示当前项页码，{active}表示当前项为激活项
     * SCS::page()->create('<li class="{active}"><a href="{url}">{page}</a></li>');
     * @param string $template 分页html模板
     * @return string
     */                                    
    public function create($template = '') {
        if(!strlen($template)) $template = '<li class="{active}"><a href="{url}">{page}</a></li>';
        $url = $this->rebuildUrl();
        $totalPage = ceil($this->total/$this->size);
        $numToShow = min($totalPage - 1, $this->column - 1);
        $firstIdx = max(1, $this->current - floor($numToShow/2));
        if($firstIdx + $numToShow > $totalPage) {
            $firstIdx = max(1, $totalPage - $numToShow);
        }
        if($totalPage <= 1) return '';
        $links = preg_replace(array('/{url}/i', '/{page}/i', '/{active}/i'), 
            array($url.'/page/1', '&lt;&lt;', (1 == $this->current) ? 'active' : ''), $template);
        for($i = $firstIdx; $i <= $numToShow + $firstIdx; $i++) {
            $links .= preg_replace(array('/{url}/i', '/{page}/i', '/{active}/i'), 
                array($url.'/page/'.$i, $i, ($i == $this->current) ? 'active' : ''), $template);
        }
        $links .= preg_replace(array('/{url}/i', '/{page}/i', '/{active}/i'), 
            array($url.'/page/'.$totalPage, '&gt;&gt;', ($totalPage == $this->current) ? 'active' : ''), $template);
        return $links;
    }
    
    /**
     * 重新构建url
     * @return string
     */
    protected function rebuildUrl() {
        $url = SCS::url()->create(SCS::request()->controller.'/'.SCS::request()->action);
        foreach(SCS::request()->param() as $param=>$value) {
            if(0 === strcasecmp('page', $param)) continue;
            $url .= '/'.$param.'/'.urlencode($value);
        }
        return $url;
    }
}